﻿using DiLe.Mes.Application.Local;
using DiLe.Mes.Model.Common.APP;
using DiLe.Mes.Model.Local.Abnormal.Entity;
using DiLe.Mes.Model.Local.Entity;
using Microsoft.AspNetCore.Authorization;

namespace DiLe.Mes.Local.Controllers.APP {
    /// <summary>
    /// 
    /// </summary>
    [ApiExplorerSettings(GroupName = ApiLocalGroupConst.Other)]
    [AllowAnonymous]
    public class AppController : ApiBaseController {

        private readonly LocalClient _localClient;
        private readonly AbnormalClient _abnormalClient;
        private readonly APPClient _appClient;

        /// <summary>
        /// 构造函数
        /// </summary>
        public AppController(LocalClient localClient, AbnormalClient abnormalClient, APPClient aPPClient) {
            _localClient = localClient;
            _abnormalClient = abnormalClient;
            _appClient = aPPClient;
        }

        /// <summary>
        /// PLC点位数据传输-成型机
        /// </summary>
        /// <param name="entitys"></param>
        [HttpPost, AllowAnonymous]
        public async Task<ApiResult> UploadPointInfo(List<PointInfoEntity> entitys) {
            var res = await _localClient.InsertPointInfo(entitys);
            return res ? Success() : Fail();
        }
        /// <summary>
        /// PLC点位数据传输-1311
        /// </summary>
        /// <param name="entitys"></param>
        [HttpPost, AllowAnonymous]
        public async Task<ApiResult> Upload1311PointInfo(List<OtherPointInfoEntity> entitys) {
            var res = await _localClient.Insert1311PointInfo(entitys);
            return res ? Success() : Fail();
        }
        /// <summary>
        /// PLC点位数据传输-切边机
        /// </summary>
        /// <param name="entitys"></param>
        [HttpPost, AllowAnonymous]
        public async Task<ApiResult> UploadTrimPointInfo(List<TrimPointInfoEntity> entitys) {
            var res = await _localClient.InsertTrimPointInfo(entitys);
            return res ? Success() : Fail();
        }
        /// <summary>
        /// PLC点位数据传输-AOI
        /// </summary>
        /// <param name="entitys"></param>
        [HttpPost, AllowAnonymous]
        public async Task<ApiResult> UploadAOIPointInfo(List<AOIPointInfoEntity> entitys) {
            var res = await _localClient.InsertAOIPointInfo(entitys);
            return res ? Success() : Fail();
        }
        /// <summary>
        /// PLC点位数据传输-电能表
        /// </summary>
        /// <param name="entitys"></param>
        [HttpPost, AllowAnonymous]
        public async Task<ApiResult> UploadEMPointInfo(List<EMPointInfoEntity> entitys) {
            var res = await _localClient.InsertEMPointInfo(entitys);
            return res ? Success() : Fail();
        }
        /// <summary>
        /// PLC点位数据传输-流量计
        /// </summary>
        /// <param name="entitys"></param>
        [HttpPost, AllowAnonymous]
        public async Task<ApiResult> UploadFMPointInfo(List<FMPointInfoEntity> entitys) {
            var res = await _localClient.InsertFMPointInfo(entitys);
            return res ? Success() : Fail();
        }


        /// <summary>
        /// APP更新
        /// </summary>
        /// <param name="appName"></param>
        /// <param name="deviceNo"></param>
        /// <returns></returns>
        [HttpGet, AllowAnonymous]
        public IActionResult UpdateNewApk(string appName, string deviceNo) {
            // 指定文件的路径
            string directoryPath = Path.Combine(AppContext.BaseDirectory, $"{deviceNo}");
            if (!Directory.Exists(directoryPath)) {
                Directory.CreateDirectory(directoryPath);
            }
            var filePath = Path.Combine(directoryPath, appName);
            // 检查文件是否存在
            if (!System.IO.File.Exists(filePath)) {
                return NotFound("文件不存在");
            }
            // 打开文件流
            var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            // 返回文件
            return File(fileStream, "application/octet-stream", appName);
        }
        #region 报警信息
        /// <summary>
        /// 开始报警
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<AlarmTempInfoEntity?>> StartAlarmAsync(AlarmTempInfoEntity alarmInfo) {
            AlarmTempInfoEntity? result = null;
            if (alarmInfo == null || alarmInfo.AlarmData == null || alarmInfo.AlarmData.IsNullOrEmpty()) {
                return Success(result);
            }
            alarmInfo.AlarmData = alarmInfo.AlarmData.Replace("LLDW10产线-", "");
            result = await _abnormalClient.InsertAlarmTempInfo(alarmInfo);
            return Success(result);
        }
        /// <summary>
        /// 查看报警
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<AlarmTempInfoEntity>> QueryAlarmAsync(string deviceNo, string alarmData) {
            alarmData = alarmData.Replace("LLDW10产线-", "");
            var result = await _abnormalClient.GetAlarmTempInfoAsync(p => p.DeviceNo == deviceNo && p.AlarmData == alarmData);
            return Success(result);
        }
        /// <summary>
        /// 结束报警
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<bool>> EndAlarmAsync(string deviceNo, string alarmData) {
            var result = await _abnormalClient.DeleteAlarmTempInfo(deviceNo, alarmData);
            return Success(result);
        }
        #endregion
        #region 设备运行
        /// <summary>
        /// 上传设备运行时间
        /// 0=设备启动 1=设备运行 2=设备急停 3=设备暂停 4=设备停止
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ApiResult UploadEquipmentDateTime(string deviceNo, int type) {
            var date = DateTime.Now.Date;
            if (DateTime.Now < date.AddHours(8)) {
                date = date.AddDays(-1);
            }
            if (type == 0) {
                var om = _appClient.GetEquipmentOperation(p => p.DeviceNo == deviceNo && p.IsFinish == false);
                if (om != null) {
                    om.EndTime = DateTime.Now;
                    om.IsFinish = true;
                    _appClient.SaveEquipmentOperation(om);
                }
                var m = new EquipmentOperationEntity() {
                    StartTime = DateTime.Now,
                    OperationDateTime = date,
                    DeviceNo = deviceNo,
                    IsFinish = false,
                };
                _appClient.SaveEquipmentOperation(m);
            } else if (type == 4) {
                var m = _appClient.GetEquipmentOperation(p => p.DeviceNo == deviceNo && p.IsFinish == false);
                if (m != null) {
                    m.EndTime = DateTime.Now;
                    m.IsFinish = true;
                    _appClient.SaveEquipmentOperation(m);
                }
            }
            return Success();
        }
        #endregion
    }
}
